<template>
    <!-- Dialog 对话框 element-plus 弹窗
    Tree 树形控件 element-plus -->
    <div>
    <!-- 引入自定义头部 -->
    <panel-head :route="route" />
    <div class="btns">
    <el-button :icon="Plus"  types="primary" @click="open(null)" size="small">新增</el-button>
    </div>
    <!-- 权限列表 -->
    <el-table :data="tableData.list" style="width:100%">
        <!-- 如果不自定义列里面的内容，直接用单标签就行 -->
        <el-table-column prop="id" label="id" />
        <el-table-column prop="name" label="昵称" />
        <el-table-column prop="permissionName" label="菜单权限" width="500px" />
        <el-table-column label="操作">
            <template #default="scope">
                <el-button type="primary" @click="open(scope.row)">编辑</el-button>
            </template>
        </el-table-column>

    </el-table>
    <!-- 分页组件 -->
     <div class="pagination-info">
         <el-pagination
      v-model:current-page="paginationData.pageNum"
      :page-size=" paginationData.pageSize"
      :background="false"
      size="small"
      layout="total, prev, pager, next"
      :total="tableData.total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
         />
     </div>
    <!-- 编辑弹窗 -->
     <el-dialog
     v-model="dialogFormVisable"
     :before-close="beforeClose"
     title="添加权限"
     width="500px"

     >
     <!-- 编辑表单 -->
      <!-- el-form 组件提供了很多内置方法，ref="formRef"可以通过 formRef.value 访问到 el-form 组件的实例 -->
     <el-form
     ref="formRef"
     label-width="100px"
     label-position="left"
     :model="form"
     :rules="rules"
     >
     <el-form-item v-show="false" prop="id">
        <el-input v-model="form.id" />
     </el-form-item>
     <el-form-item label="名称" prop="name">
        <el-input v-model="form.name" placeholder="请填写权限名称"/>
     </el-form-item>
     <el-form-item label="权限" prop="permissions">
        <el-tree 
        ref="treeRef"
        style="max-width: 600px;"
        :data="permissionData"
        node-key="id"
        show-checkbox
        :default-checked-keys="defaultKeys"
        :default-expanded-keys="[2]"
        />
     </el-form-item>
     </el-form>
     <template #footer>
     <div class ="dialog-footer">
        <el-button type="primary" @click="confirm(formRef)">确认</el-button> 
     </div>
    </template>

     </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive ,onMounted, nextTick} from 'vue'
import { userGetMenu ,userSetMenu ,menuList} from '../../../api'
import { Plus } from '@element-plus/icons-vue'
import { useRoute } from 'vue-router'

const route = useRoute()
onMounted(() => {
    //菜单数据
    userGetMenu().then(({ data }) => {
        console.log(data)
        //双层 data 通常是因为接口响应格式为 { data: { ... }, code: 200 }）。
        permissionData.value=data.data
    })
    getListData()
})

//列表数据
const tableData = reactive({
    list: [],
    total:0
})
//树形菜单权限数据
const permissionData = ref([])

//弹窗的显示隐藏
const dialogFormVisable = ref(false)
//打开弹窗
const open = (rowData = {}) => {
    //显示弹窗
    dialogFormVisable.value = true
    //弹窗打开form生成是异步的
    //等待弹窗 DOM 渲染完成后，再执行数据赋值（避免 ref 未初始化）
    nextTick(() => {
        if (rowData) {
            //进行属性合并
            Object.assign(form, { id: rowData.id, name: rowData.name })
            //设置树形组件默认选中值（编辑时回显）
            treeRef.value.setCheckedKeys(rowData.permission)
        }
    })
}

// 分页参数
const paginationData = reactive({
    pageNum: 1,
    pageSize: 10
})
const handleSizeChange = (val) => {
    paginationData.pageSize = val
    getListData()
}
const handleCurrentChange = (val) => {
    paginationData.pageNum = val
    getListData()
}


//请求列表数据
const getListData = () => {
    menuList(paginationData).then(({ data }) => {    
        const { list, total } = data.data
        tableData.list = list
        tableData.total = total

    })
}


const formRef = ref()

//form的数据
const form = reactive({
    name: '',
    permissions: '',
    id: ''
})

//关闭弹窗的回调
const beforeClose = () => {
    dialogFormVisable.value = false
    //重置表单
    formRef.value.resetFields()
    //tree选择重置
    treeRef.value.setCheckedKeys(defaultKeys)
}
//默认选中权限
const defaultKeys = [4, 5]
const treeRef = ref()
//表单校验
const rules = reactive({
    name: [{required:true,trigger:'blur',message:'请输入权限名称'}]
})

//表单提交
const confirm = async (formEl) => {
    if (!formEl) return
    //手动触发表单校验
    await formEl.validate((valid, fields) => {
        if(!formEl) return
        if (valid) {
            //获取到选择的checkbox数据
           const permissions = JSON.stringify(treeRef.value.getCheckedKeys())
            userSetMenu({ name: form.name, permissions, id: form.id }).then(({ data }) => {
                console.log(data)
                //提交成功后关闭弹窗并重置状态
                beforeClose()
                //刷新表格数据，显示最新结果
                getListData()
            })
        } else {
        console.log('error submit!', fields)
        }

    })
}

</script> 

<style scoped>
.btns{
    padding: 10px 0 10px 10px;
    background-color: #fff;
}
</style>